#This code fetches image art from amazon. But TBH amazon API is overkil for this.
#Discogs has better images so let's use that.
#This is mothballed.

from stages import GlobalStage
import SOAPpy
from config import Config
import urllib
import os
from mutagen.flac import FLAC

codes = ["US","UK"] #,"CA","FR","DE","CA","JP"]
def makeUrl(code):
    if code == "":
        return 'http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl'
        #return 'http://webservices.amazon.com/onca/soap?Service=AWSECommerceService'
    return 'http://webservices.amazon.com/AWSECommerceService/%s/AWSECommerceService.wsdl' % code

proxies = []
for code in codes:
    proxy = SOAPpy.WSDL.Proxy(makeUrl(code))
    proxies += [proxy]

class FetchCoverArt(GlobalStage):
    file = "cover.jpg"
        
    def __init__(self, shagger):
        GlobalStage.__init__(self, shagger) 
    
    def preamble(self):
        return "Fetch cover art"
    
    def canWork(self):
        files = self.shagger.fileSubset("")
        for file in files:
            if file.endswith(self.file):
                return False
        return True
    
    def work(self):
        #Need to fetch ASIN
        files = self.shagger.fileSubset("flac")
        audio = FLAC( files[0] )
        if not audio.has_key("ASIN"):
            self.shagger.log("No ASIN found so can't fetch cover art")
            return True
        asin = audio["ASIN"][0]        
        
        request = { 
            'ResponseGroup': 'Images',
            'AWSAccessKeyId':   Config['amazonid'] ,
            'ItemId': asin, 
            'ItemID': asin, 
            'ItemType': 'ASIN',           
            }
        
        self.shagger.log ('Amazon.com search for  " ' + str(request))
        ans = None
        for proxy in proxies:
            try:
                results = proxy.ItemLookup(request)
                self.shagger.log("Amazon result: %s" % str(results))
                req = results.Items.Request
                if(req.IsValid == 'True' and not req._asdict().has_key("Errors")):
                    ans = results
                    break
            except Exception, e:
                self.shagger.log ( e )
                self.shagger.log ( "Proxy failed %s"  % proxy )
        
        if ans == None:
            print("Not found, try more amzons?")
            return False
        
        ims = ans.Items.Item
        self.shagger.log ('good request' )
        '''
        for key in ims._keys():
            url = ims[key].URL
            print "%s: %s" % (key, url)
        '''
        f = self.filename(self.file)
        
        if "LargeImage" in ims._keys():
            key = "LargeImage"
        elif "MediumImage" in ims._keys():
            key = "MediumImage"
        else:
            self.shagger.log("Couldn't find suitable image")
            return False
        
        urllib.urlretrieve(ims[key]['URL'], f)            
        return True
        
                


